//
//  PCPhotoExhibitionVC.m
//  PhotoCircle
//
//  Created by wujungao on 12/10/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCPhotoExhibitionVC.h"
#import "photoExhibitionLeftCell.h"
#import "photoExhibitionRightCell.h"
#import "bannerCell.h"
#import "photoExhibitionHeadView.h"
#import "footerView.h"
#import "PCShowPhotoCommVC.h"
#import "SVPullToRefresh.h"
#import "fetchData.h"
#import "NSDate+Convenience.h"
#import "PCPhotoMatchColumnVC.h"
#import "PCJoinPhotoMatchVC.h"
#import "PCPhotoUploadVC.h"
#import "bannerModel.h"
#import "photoExhibitionModel.h"
#import "photoExhibitionDetailModel.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "nodataCell.h"

#import "GMBannerKit.h"

#define headViewH 30
#define BANNER_HEIGHT (9*SCREEN_W)/16.0
#define cellW  (SCREEN_W/2.0)
#define cellH  (0.5+5+imageH+5+12+5)
#define imageW ((SCREEN_W/2.0) - 15)//cellW/H and imageH come from imageW,so the imageW is base value.
#define imageH ((imageW * 9) / 16)

static NSString *leftCellID=@"photoExhibitionLeftCell";
static NSString *rightCellID=@"photoExhibitionRightCell";
static NSString *headID=@"head";
static NSString *footerID=@"footer";
static NSString *bannerCellID=@"bannerCell";
static NSString *nodataCellID=@"nodataCell";

@interface PCPhotoExhibitionVC() <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,PlusDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,GMBannerViewDelegate>

@property(strong,nonatomic)GMBannerView *gmBannerView;

@property (strong,nonatomic) UICollectionView *photoExhibitionView;
@property (assign,nonatomic) CGRect photoExhibitionViewRect;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *topView;

@property(strong,nonatomic)NSMutableArray *bannerModelArray;
@property(strong,nonatomic)NSMutableArray *bannerImageURLArray;
@property(strong,nonatomic)NSMutableArray *bannerTitleArray;
@property(strong,nonatomic)NSMutableArray *photoExhibitionModelArray;
@property(assign,nonatomic)NSInteger pageNum;

@property(nonatomic,strong)bannerCell *bannerCell;
@property(nonatomic,assign)BOOL nodataFlag;

@end

@implementation PCPhotoExhibitionVC

#pragma mark - PCPhotoExhibitionVC method
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.alpha=1.0;
    self.photoExhibitionView.alwaysBounceVertical=YES;
    MCShowNavBar();
    MCHiddenNavBackButton();
    MCHiddenTabBar();
    MCShowBottomView();
    MCShowPlusBackgroundView();
    MCPlusDelegate();
    [self configNavAndTabBar];
    [self configRedLineView];
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    //custom views
    [self configNavAndTabBar];
    [self configPhotoExhibitionView];
    
    //data
    [self configRefresh];
    [self toRefresh];
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
}

#pragma mark - config view method
-(void)configRefresh{
    
    __weak typeof(self) weakSelf=self;
    
    [self.photoExhibitionView addPullToRefreshWithActionHandler:^{
        [weakSelf toRefresh];
    }];
    [self.photoExhibitionView addPullToRefreshWithTriggerHandler:^{
        [weakSelf toTrigger];
    }];
    
    [self.photoExhibitionView addInfiniteScrollingWithActionHandler:^{
        
        [weakSelf toLoadMore];
    }];
}

-(void)configNavAndTabBar{
    
    self.titleLabel.text=@"影展";
}

-(void)configRedLineView{
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:1.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [self.view addSubview:lineView];
}

-(void)configPhotoExhibitionView{
    
    self.photoExhibitionView.delegate=self;
    self.photoExhibitionView.dataSource=self;
    self.photoExhibitionView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.photoExhibitionView];
}

-(void)configBannerView{
    
    [self.gmBannerView configViewWithBannerArray:self.bannerModelArray placeHolderImage:nil];
    [self.bannerCell addSubview:self.gmBannerView];
}

#pragma mark - private method
-(void)clickedBannerViewImageViewWithIndex:(NSInteger)index{
    //跳转大赛页面
    NSString *uuid=(((bannerModel *)self.bannerModelArray[index]).UUID);
    
    UIStoryboard *matchColumnStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCPhotoMatchColumnVC *matchColumnVC=[matchColumnStory instantiateViewControllerWithIdentifier:@"PCPhotoMatchColumnVC"];
    [matchColumnVC passUUID:uuid];
    
    [self.navigationController pushViewController:matchColumnVC animated:YES];
}

-(void)copyContentToBanner{
    
    [self configBannerView];
}

#pragma mark - fetch data method
-(void)toRefresh{
    
    self.pageNum=1;
    NSDictionary *dict=@{@"page":@1};
    
    [[fetchData shared] fetchExhibitionListWithParameterDict:dict successBlock:^(NSMutableArray *bannerModelArray, NSMutableArray *photoExhibitionModelArray) {
        
        [self.photoExhibitionView.pullToRefreshView stopAnimating];
        self.bannerModelArray=[bannerModelArray mutableCopy];
        
        //banner data
        [self copyContentToBanner];
        
        self.photoExhibitionModelArray=[photoExhibitionModelArray mutableCopy];
        if(photoExhibitionModelArray.count==0){
            
            self.nodataFlag=YES;
        }
        
        [self.photoExhibitionView reloadData];
        
    } failBlock:^{
        //请求错误
        [self.photoExhibitionView.pullToRefreshView stopAnimating];
        [GMTipsHelper showBadNetwork];
    }];
}

-(void)toTrigger{
    
    NSString *lastUpdateTime = [UserDefaults_GetObject(NSStringFromClass([self class])) sinceNowDescription];
    if(!lastUpdateTime.length)
        lastUpdateTime = NSLocalizedString(STR_NeverRefresh, );
    NSString *lastUpdateStr = PCStrFormat(@"%@%@", NSLocalizedString(STR_LastAt, ), lastUpdateTime);
    [self.photoExhibitionView.pullToRefreshView setSubtitle:lastUpdateStr forState:SVPullToRefreshStateAll];

}

-(void)toLoadMore{
    
    NSDictionary *dict=@{@"page":@(self.pageNum+1)};
    
    [[fetchData shared] fetchExhibitionListWithParameterDict:dict successBlock:^(NSMutableArray *bannerModelArray, NSMutableArray *photoExhibitionModelArray) {
        
        [self.photoExhibitionView.infiniteScrollingView stopAnimating];
        self.pageNum +=1;
        self.bannerModelArray=[bannerModelArray mutableCopy];
        self.photoExhibitionModelArray=[photoExhibitionModelArray mutableCopy];
        
    } failBlock:^{
        //请求错误
        [self.photoExhibitionView.infiniteScrollingView stopAnimating];
        [GMTipsHelper showBadNetwork];
    }];
}

#pragma mark - property
-(GMBannerView *)gmBannerView{
    
    if(_gmBannerView==nil){
        
        UINib *bannerNib=[UINib nibWithNibName:@"GMBannerView" bundle:[NSBundle mainBundle]];
        _gmBannerView=[[bannerNib instantiateWithOwner:nil options:nil] firstObject];
        
        _gmBannerView.frame=CGRectMake(0,0, SCREEN_W, BANNER_HEIGHT);
        _gmBannerView.bDelegate=self;
    }
    
    return _gmBannerView;
}

-(NSMutableArray *)bannerTitleArray{
    
    if(_bannerTitleArray==nil){
        
        _bannerTitleArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _bannerTitleArray;
}

-(NSMutableArray *)bannerModelArray{
    
    if(_bannerModelArray==nil){
        
        _bannerModelArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _bannerModelArray;
}

-(NSMutableArray *)bannerImageURLArray{
    
    if(_bannerImageURLArray==nil){
        
        _bannerImageURLArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _bannerImageURLArray;
}

-(NSMutableArray *)photoExhibitionModelArray{
    
    if(_photoExhibitionModelArray==nil){
        
        _photoExhibitionModelArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _photoExhibitionModelArray;
}

-(UICollectionView *)photoExhibitionView{
    
    if(_photoExhibitionView==nil){
        
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
        
        _photoExhibitionView=[[UICollectionView alloc] initWithFrame:[self photoExhibitionViewRect] collectionViewLayout:flowLayout];
        
        UINib *nodataNib=[UINib nibWithNibName:@"nodataCell" bundle:[NSBundle mainBundle]];
        [_photoExhibitionView registerNib:nodataNib forCellWithReuseIdentifier:nodataCellID];
        
        UINib *leftcellNib=[UINib nibWithNibName:@"photoExhibitionLeftCell" bundle:[NSBundle mainBundle]];
        [_photoExhibitionView registerNib:leftcellNib forCellWithReuseIdentifier:leftCellID];
        UINib *rightcellNib=[UINib nibWithNibName:@"photoExhibitionRightCell" bundle:[NSBundle mainBundle]];
        [_photoExhibitionView registerNib:rightcellNib forCellWithReuseIdentifier:rightCellID];
        
        UINib *headNib=[UINib nibWithNibName:@"photoExhibitionHeadView" bundle:[NSBundle mainBundle]];
        [_photoExhibitionView registerNib:headNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headID];
        
        [_photoExhibitionView registerClass:[bannerCell class] forCellWithReuseIdentifier:bannerCellID];
        [_photoExhibitionView registerClass:[footerView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerID];
    }
    
    return _photoExhibitionView;
}

-(CGRect)photoExhibitionViewRect{
    
    if(CGRectIsEmpty(_photoExhibitionViewRect) || CGRectIsNull(_photoExhibitionViewRect)){
        
        CGFloat x=0;
        CGFloat y=0;
        CGFloat h=SCREEN_H-y-bottomViewH;
        _photoExhibitionViewRect=CGRectMake(x, y, SCREEN_W, h);
    }
    
    return _photoExhibitionViewRect;
}

#pragma mark - UICollecitonView Delegate,dataSource,flowlayout delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(section==0){
        
        return 1;
        
    }else{
        
        NSInteger num;
        
        if(self.nodataFlag){
            
            num= (self.photoExhibitionModelArray.count==0 ? 1 : self.photoExhibitionModelArray.count);
            
        }else{
            
            num=self.photoExhibitionModelArray.count;
        }
        
        return num;
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if((indexPath.section==0) && ([kind isEqualToString:UICollectionElementKindSectionFooter])){
        
        footerView *footer=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerID forIndexPath:indexPath];
        
        return footer;

    }else if((indexPath.section==1) && ([kind isEqualToString:UICollectionElementKindSectionHeader])){
        
        photoExhibitionHeadView *headerView;
        
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headID forIndexPath:indexPath];
        
        [headerView configHeadViewWithTitle:@"影展每周详情"];
        [headerView configView];
        
        return headerView;
        
    }else{
        
        return nil;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section==0){
        
        self.bannerCell=[collectionView dequeueReusableCellWithReuseIdentifier:bannerCellID forIndexPath:indexPath];
        
        return self.bannerCell;
        
    }else if(self.photoExhibitionModelArray.count!=0){
        
        NSString *imageURL=((photoExhibitionModel *)self.photoExhibitionModelArray[indexPath.item]).imageURL;
        NSString *title=((photoExhibitionModel *)self.photoExhibitionModelArray[indexPath.item]).title;
        
        if(indexPath.item%2==0){
            //left cell
            photoExhibitionLeftCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:leftCellID forIndexPath:indexPath];
            
            [cell configCellWithImageURL:imageURL andTitle:title];
            
            return cell;
            
        }else{
            //right cell
            photoExhibitionRightCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:rightCellID  forIndexPath:indexPath];
            [cell configCellWithImageURL:imageURL andTitle:title];
            
            return cell;
        }
        
    }else{
        
        nodataCell *nodataCell=[collectionView dequeueReusableCellWithReuseIdentifier:nodataCellID forIndexPath:indexPath];
        return nodataCell;
        
    }
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.0;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if(section==0){
        
        return CGSizeZero;
        
    }else{
        
     return CGSizeMake(SCREEN_W, headViewH);
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeZero;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section==0){
 
        return CGSizeMake(SCREEN_W, BANNER_HEIGHT);
        
    }else{
        
        CGSize cellSize=(self.photoExhibitionModelArray.count==0 ? CGSizeMake(SCREEN_W, self.photoExhibitionViewRect.size.height-BANNER_HEIGHT-headViewH) : CGSizeMake(cellW,cellH));
        
        return cellSize;
    }
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section==0){
        
        return NO;
        
    }else{
        
        BOOL seflag=(self.photoExhibitionModelArray.count==0 ? NO : YES);
        return seflag;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //跳转至影展详情页面
    UIStoryboard *showVCStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCShowPhotoCommVC *showVC=[showVCStory instantiateViewControllerWithIdentifier:@"PCShowPhotoCommVC"];
    [showVC passVCType:photoExhibitionDetailVC];
    [showVC passphotoExhibitionDetailUUID:((photoExhibitionModel *)self.photoExhibitionModelArray[indexPath.item]).UUID];
    
    [self.navigationController pushViewController:showVC animated:YES];
}

#pragma mark - plusDelegate
-(void)joinPhotoMatch{//拍照上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

-(void)albumUpload{//参赛
    UIStoryboard *joinStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCJoinPhotoMatchVC *joinVC=[joinStory instantiateViewControllerWithIdentifier:@"PCJoinPhotoMatchVC"];
//    [joinVC passVCType:photoExhibitionVC];
    [self.navigationController pushViewController:joinVC animated:YES];
    simulationPressPlusBtn();
}

-(void)photoGraphUpload{//相册上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - image picker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *imageURL=[info objectForKey:UIImagePickerControllerReferenceURL];
    __block NSDictionary *metadataDict;
    
    if(picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){
        //相册
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            metadataDict=representation.metadata;
            
            //upload图片
            [self uploadImage:image withImageMetaData:metadataDict];
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageURL
                       resultBlock:resultblock
                      failureBlock:nil];
        
    }else{
        //拍照
        metadataDict=[info valueForKey:UIImagePickerControllerMediaMetadata];
        //upload图片
        [self uploadImage:image withImageMetaData:metadataDict];
    }
}

-(void)uploadImage:(UIImage *)image withImageMetaData:(NSDictionary *)imageMetaData{
    
    UIStoryboard *photoUploadStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCPhotoUploadVC *photoUploadVC=[photoUploadStory instantiateViewControllerWithIdentifier:@"PCPhotoUploadVC"];
    
    [photoUploadVC passImage:image withImageMetaDat:imageMetaData];
    
    [self.navigationController pushViewController:photoUploadVC animated:YES];
    
    simulationPressPlusBtn();
}

#pragma mark - GMBannerViewDelegate
-(void)bannerViewPressedAt:(NSInteger)index{
    
    [self clickedBannerViewImageViewWithIndex:index];
}

@end
